package com.innovation.ic.cc.base.thread.listener.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.innovation.ic.cc.base.model.cc.erp9_pvesiteuser.UsersTopView;
import com.innovation.ic.cc.base.pojo.constant.handler.RabbitMqConstants;
import com.innovation.ic.cc.base.service.cc.UserService;
import com.rabbitmq.client.*;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @desc   监听密码被重置监听密码被重置队列
 * @author swq
 * @time   2023年5月17日10:12:24
 */
public class ListenModelUpdatePassWordQueueThread extends AbstractRabbitmqThread implements Runnable {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Channel channel;
    private UserService userService;

    public ListenModelUpdatePassWordQueueThread(Channel channel, UserService userService) {
        this.channel = channel;
        this.userService = userService;
    }

    @SneakyThrows
    public void run() {
        String exchange = RabbitMqConstants.CC_ERP_EXCHANGE;
        String routingKey = RabbitMqConstants.ERP_CC_RESET_USERS;
        //String queue = RabbitMqConstants.ERP_TO_SC_QUEUE_NAME;
        final String queue = routingKey;
        channel.queueBind(queue, exchange, routingKey);
        channel.queueDeclare(queue, true, false, false, null);
        channel.exchangeDeclare(exchange, RabbitMqConstants.DIRECT_TYPE, true);
        Consumer callback = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String bodyString = new String(body);
                logger.info("接收到的队列:[{}]的消息为:[{}]", queue, bodyString);
                try {
                    if (!Strings.isNullOrEmpty(bodyString)) {
                        // 获取消息体中的数据内容
                        String messageBody = getMessageBody(bodyString);
                        if (!Strings.isNullOrEmpty(messageBody)) {
                            UsersTopView usersTopView = JSONObject.parseObject(messageBody, UsersTopView.class);
                            if (usersTopView != null) {
                                userService.handleModelUpdatePassWordMqMsg(usersTopView);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("监听队列:[{}]时出现问题,原因:", queue, e);
                }
            }
        };
        channel.basicConsume(queue, true, callback);
    }
}